package com.smh.hmdianping.interceptor;

import com.smh.hmdianping.constant.UserConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author shiminghui
 * @date 2025/3/27 16:55
 * @description: TODO
 */
@Component
public class RefreshInterceptor implements HandlerInterceptor, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String token = request.getHeader("token");
        if (token == null) {
            return true;
        }
        // 刷新token
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(UserConstant.USER_PREFIX + token);
        if (entries.isEmpty()) {
            return true;
        }
        stringRedisTemplate.expire(UserConstant.USER_PREFIX + token, 30, TimeUnit.MINUTES);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
